import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { AppController } from '@/app.controller';
import { AppService } from '@/app.service';
import { Test2Module } from '@/api/test2/test2.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { LoggerMiddleware } from '@/middleware/logger.middleware';
import { AuthModule } from 'api/auth/auth.module';
import { UserModule } from 'api/user/user.module';
// 用于将数据库字段的下划线转换成驼峰
import { SnakeNamingStrategy } from 'typeorm-naming-strategies';
import { APP_GUARD } from '@nestjs/core';
import { AuthGuard } from '@/guard/auth.guard';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: '123123123',
      database: 'test_db',
      autoLoadEntities: true,
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      synchronize: true,
      namingStrategy: new SnakeNamingStrategy(), // 使用自定义命名策略
    }),
    Test2Module,
    UserModule,
    AuthModule,
  ],
  controllers: [AppController],
  providers: [
    AppService,
    // 将jwt校验的守卫注入到NestJS容器中，并设置为全局守卫
    {
      provide: APP_GUARD,
      useClass: AuthGuard,
    },
  ],
})

// 在module中实现NestModule接口，并实现configure方法，在其中调用MiddlewareConsumer的apply方法来注册中间件。
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('test2');
  }
}
